(function(){
    
    const base = 'http://localhost:8080' ;

    const $ = selector => document.querySelector(selector) ;
    const $$ = selector => document.querySelectorAll(selector);

    const btn = $( '.button-wrapper>button' );

    const preAdd = evt => {
        evt.stopPropagation(); // 阻止事件传播
        let name = $('input[name=name]').value ;
        let genders = Array.from( $$('input[name=gender]') );
        let radio = genders.find( r => r.checked );
        let gender = radio ? radio.value : null ;
        let birthdate = $( 'input[name=birthdate]').value;
        let panda = {
            name: name ,
            gender: gender ,
            birthdate: birthdate
        }
        let url = base + '/panda'
        add( url , panda );
    } 

    btn.addEventListener( 'click' , preAdd , true );

    const list = $( '.panda-list' );

    list.addEventListener( 'click' , evt => {
        evt.preventDefault(); // 阻止事件默认行为
        let t = evt.target ;
        let id = t.dataset.id ; // 确定熊猫的id
        let op = t.dataset.type ; // 确定操作类型
        switch(op){
            case 'update': 
                load(id).then( edit );
                break;
            case 'remove': 
                remove(id); 
                break;
        }
    } , true );

    const edit = p => {
        console.log( p );

        $('input[name=name]').value = p.name ;

        Array.from( $$('input[name=gender]') ).forEach( radio => {
            if( radio.value === p.gender ) {
                radio.checked = true ;
                return ;
            }
            radio.checked = false ;
        });

        $('input[name=birthdate]').value = p.birthdate;

        let btn = $('.button-wrapper>button');
        btn.innerHTML = '修改' ;
        // 移除原来的事件监听器
        btn.removeEventListener( 'click' , preAdd , true );
        // 添加新的事件监听器
        btn.addEventListener( 'click' , update , true );

        const editor = $( '.editor-wrapper' );
        // <input type="hidden" name="id" value="2">
        let hide = document.createElement( 'input' );
        hide.type = 'hidden' ;
        hide.name = 'id' ;
        hide.value = p.id ;
        // 将 hide 元素添加到 editor 内部末尾
        editor.appendChild( hide );
    }

    const update = evt =>{
        evt.preventDefault();
        evt.stopPropagation();

        let p = {
            id: $('.editor-wrapper>input[type=hidden]').value ,
            name: $('input[name=name]').value ,
            gender: Array.from( $$('input[name=gender]')).find( r => r.checked ).value ,
            birthdate: $('input[name=birthdate]').value
        }
        
        let url = base + '/panda' ;

        fetch( url , { 
            method: 'PUT' , 
            headers: {
                'content-type': 'application/json'
            },
            body: JSON.stringify( p )
        }).then( response => response.json() )
        .then( result => {
            if( result.success ) {
                console.log( result.message );
                // 重新加载
                loadAll();
                // 重置编辑区域
                resetEditor();
            }
        })
    }

    // 删除
    const remove = id => {
        let url = base + `/panda/${id}` ;
        fetch( url , { method: 'DELETE' } ).then( response => response.json() )
        .then( result => {
            if( result.success ) {
                console.log( result.message );
                // 重新加载数据
                loadAll();
            }
        });
    }

    // 添加 
    const add = (url,params) => {
        let options = {
            method: 'POST',
            headers: {
                'content-type': 'application/json'
            },
            body: JSON.stringify( params )
        }
        fetch( url , options )
        .then( response => response.json() )
        .then( data => {
            if( data.success ) {
                console.log( data.message );
                resetEditor();
                loadAll();
                return ;
            }
        });
    }

    // 重置编辑区域
    const resetEditor = () => {
        let input = $( 'input[name=name]' );
        input.value = '' ;

        let radios = $$( 'input[name=gender]' );
        Array.from( radios ).forEach( r => r.checked = false );

        let date = $( 'input[name=birthdate]' );
        date.value = '' ;

        let btn = $( '.button-wrapper>button' );
        btn.innerHTML = '添加' ;

        const editor = $( '.editor-wrapper' );
        let hide = editor.querySelector( 'input[type=hidden]' );
        if( hide ) {
            editor.removeChild( hide );
        }

        // 移除原来的事件监听器
        btn.removeEventListener( 'click' , update , true );
        // 添加新的事件监听器
        btn.addEventListener( 'click' , preAdd , true );

    }

    // 查询单个Panda并返回一个Promise实例
    const load = id => {
        let url = base + `/panda/${id}` ;
        let promise = fetch(url, { method: 'GET' } );
        promise = promise.then( response => response.json() );
        return promise ;
    }

    // 查询
    const loadAll = () => {
        let url = base + `/panda` ;
        let p = fetch( url , { method: 'GET' } );
        p.then( response => response.json() )
         .then( pandas => {
            if( pandas.length === 0 ) {
                list.innerHTML = '暂无数据';
                return;
            }
            // 清空列表中原来的内容
            list.innerHTML = "" ;
            // 遍历数组将每个元素展示到页面上
            pandas.forEach( p => {
                let e = document.createElement( 'div');
                e.classList.add( 'panda' );
                e.innerHTML = `<span class="id">${p.id}</span>
                                <span class="name">${p.name}</span>
                                <span class="gender">${p.gender}</span>
                                <span class="birthdate">${p.birthdate}</span>
                                <span class="operation">
                                    <a data-id="${p.id}" data-type="update">修改</a>
                                    <a data-id="${p.id}" data-type="remove">删除</a>
                                </span>`;
                list.appendChild( e );
            });
        });
    }

    // 调用 loadAll 方法完成数据加载
    loadAll();

})();